package com.epam.client.controller;

import java.io.IOException;

import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;

import com.epam.DAO.ClientDAO;
import com.epam.DAO.Factories.DAOFactory;
import com.epam.entity.Client;

import com.epam.utils.JsfUtil;

public class ClientLoginBean {

	private static Logger log = Logger.getLogger(ClientLoginBean.class);

	private DAOFactory daoFactory;
	private ClientDAO clientDAO;

	private String login;
	private String pass;

	public ClientLoginBean() {
		daoFactory = DAOFactory
				.getDAOFactory(DAOFactory.CURRENT_IMPLEMENTATION);
		clientDAO = daoFactory.getClientDAO();
	}

	public String getLogin() {
		return login;
	}

	public void setLogin(String login) {
		this.login = login;
	}

	public String getPass() {
		return pass;
	}

	public void setPass(String pass) {
		this.pass = pass;
	}

	public String tryLogin() {
		log.debug("tried to check login" + " " + login + " " + pass);

		Client client = clientDAO.read(login, pass);
		
		if (client != null) {
			log.debug("login success");
			JsfUtil.createSession();
			JsfUtil.setAttribute("client", client);
			return "success";
		} else {
			JsfUtil.addMessage("login_register_form:login", "Wrong login or password");
			log.debug("login fail");
			return "fail";
		}
	}

	public void logout() throws IOException {
		log.debug("tried to logout");

		FacesContext context = FacesContext.getCurrentInstance();
		HttpServletRequest request = (HttpServletRequest) context
				.getExternalContext().getRequest();
		request.getSession().invalidate();

		HttpServletResponse response = (HttpServletResponse) FacesContext
				.getCurrentInstance().getExternalContext().getResponse();
		response.sendRedirect("faces/index.xhtml");
	}

}
